/*
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is ST_EXT-S_UIMAST.
 *
 * The Initial Developer of the Original Code is
 * University of Rome, Tor Vergata
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 */

package it.uniroma2.art.uimast.impl;

import org.w3c.dom.Element;

/**
 * Exposes some DOM common facilities.
 * 
 * @author <a href="mailto:manuel.fiorelli@gmail.com">Manuel Fiorelli</a>
 */
public class CommonDOMFacilities {
	/**
	 * Tests if two objects are equals.
	 * 
	 * @param o1
	 *            an object
	 * @param o2
	 *            an object
	 * @return <code>true</code> iff
	 *         <code>((o1 == null) ? (o2 == null) : o1.equals(o2))</code>
	 */
	private static boolean equals(Object o1, Object o2) {
		if (o1 == null)
			return o2 == null;
		else
			return o1.equals(o2);
	}

	/**
	 * Gets an attribute. This method is needed because an attribute doesn't
	 * inherit the context namespace.
	 * 
	 * @param e
	 *            the context element
	 * @param namespaceURI
	 *            the namespace URI (may be null)
	 * @param localName
	 *            the attribute local name
	 * @return <code>true</code> iff <code>e</code> has such an attribute
	 * @see #getAttributeNS(Element, String, String)
	 */
	public static boolean hasAttributeNS(Element e, String namespaceURI,
			String localName) {
		return equals(e.lookupNamespaceURI(e.getPrefix()), namespaceURI)
				&& e.hasAttributeNS(null, localName)
				|| e.hasAttributeNS(namespaceURI, localName);
	}

	/**
	 * Gets an attribute. This method is needed because an attribute doesn't
	 * inherit the context namespace.
	 * 
	 * @param e
	 *            the context element
	 * @param namespaceURI
	 *            the namespace URI (may be null)
	 * @param localName
	 * @return the attribute value (otherwise <code>""</code>)
	 * @see #hasAttributeNS(Element, String, String)
	 */
	public static String getAttributeNS(Element e, String namespaceURI,
			String localName) {
		if (e.hasAttributeNS(namespaceURI, localName))
			return e.getAttributeNS(namespaceURI, localName);
		if (e.getNamespaceURI().equals(namespaceURI))
			return e.getAttributeNS(null, localName);
		else
			return "";
	}
}
